//
//  HMEmoticonKeyboard.swift
//  68.新工程-表情键盘_界面搭建
//
//  Created by shenzhenIOS on 16/4/18.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

/// 自定义的表情键盘
class HMEmoticonKeyboard: UIView {
    
    // 表情键盘对应的textView
    weak var textView: UITextView?
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.brownColor()
        
        // 添加控件
        addSubview(collectionView)
        addSubview(emoticonToolBar)
        addSubview(pageControl)
        
//        collectionView.addSubview(recentLabel)
        
        // 添加约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        emoticonToolBar.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
//        recentLabel.translatesAutoresizingMaskIntoConstraints = false
        
        // VFL
        // collectionView 水平,左右和父控件重合
        // H: 水平 V: 垂直
        // ||, |:父控件左边/顶部   |:父控件右边/底部
        // [cv]: 表示一个view  [:view的左边  ]: view的右边
        // views: VFL里面用到的view映射
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: ["cv" : collectionView]))
        
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: ["tb" : emoticonToolBar]))
        
        // 垂直方向, 
        // collectionView的顶部到父控件顶部0
        // collectioView的底部和emoticonToolBar的顶部重合
        // emoticonToolBar高度44
        // emoticonToolBar的底部和父控件的底部重合
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: [], metrics: nil, views: ["cv" : collectionView, "tb": emoticonToolBar]))
        
        // pageControll约束
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: emoticonToolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
        
        // 最近label
//        collectionView.addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 20))
//        
//        collectionView.addConstraint(NSLayoutConstraint(item: recentLabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 子控件的大小就确定了
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.frame.size
//        
//        recentLabel.frame = CGRect(x: collectionView.frame.width * 0.5 - recentLabel.frame.width * 0.5, y: collectionView.frame.height - recentLabel.frame.height, width: recentLabel.frame.width, height: recentLabel.frame.height)
    }

    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        cv.backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        cv.pagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        cv.bounces = false
        
        cv.dataSource = self
        cv.delegate = self
        
        cv.registerClass(HMEmoticonKeyboardPageCell.self, forCellWithReuseIdentifier: self.ReuseIdentifier)
        
        return cv
    }()
    
    /// toolBar
    private lazy var emoticonToolBar: HMEmoticonToolBar = {
        let toolBar = HMEmoticonToolBar.emoticonToolBar()
        
        // 5.设置self为代理
        toolBar.delegate = self
        
        // 默认选中第0组
//        toolBar.switchSelectButton(0)
        
        return toolBar
    }()
    
    /// pageControl
    private lazy var pageControl: UIPageControl = {
        let control = UIPageControl()
        
        control.hidden = true
        
        // 设置
        control.numberOfPages = 5
        control.currentPage = 2
        
//        control.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
//        control.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        
//        UIPageControl.printIvars()
        // _pageImage   普通的
        // _currentPageImage    选中的
        control.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        control.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        return control
    }()
    
    // collectionView模拟的组和cell数量
//    private let items = [1, 6, 4, 2]
}

// 6.实现代理协议
extension HMEmoticonKeyboard: HMEmoticonToolBarDelegate {
    /// 7.实现代理协议的方法.按钮点击
    func emoticonToolBar(toolBar: HMEmoticonToolBar, selectedButtonType type: HMEmoticonToolBarType) {
//        print("我再HMEmoticonKeyboard知道按钮被点击了,切换collectionView: \(type)")
        // 滚动到对应的组
        let indexPath = NSIndexPath(forItem: 0, inSection: type.rawValue)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        
        // 设置pageControl
        setupPageControl(indexPath)
    }
}

extension HMEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    // 有多少组,看有多少个表情包
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HMEmoticonManager.sharedManager.packageModels.count
    }
    
    // 每组有几个cell, 对应表情包里面有多少页表情要显示
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonManager.sharedManager.packageModels[section].pageEmoticons.count
    }
    
    // cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HMEmoticonKeyboardPageCell
        
//        cell.backgroundColor = UIColor.randomColor()
        cell.indexPath = indexPath
        
        // 将对应的页的表情传递给cell
        cell.pageEmoticon = HMEmoticonManager.sharedManager.packageModels[indexPath.section].pageEmoticons[indexPath.item]
        
        // 5.成为cell的代理
        cell.delegate = self
        
        return cell
    }
    
    // scrollView滚动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 判断显示哪一组
        
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
//        print("refPoint: \(refPoint)")
        
        // 获取正在显示的cell
//        let indexPath = collectionView.indexPathForItemAtPoint(refPoint)
        
        for cell in collectionView.visibleCells() {
            if cell.frame.contains(refPoint) {
                // 获取cell的indexPath
                let indexPath = collectionView.indexPathForCell(cell)
//                print("找到了indexPath: \(indexPath)")
                // 选中对应这组的按钮
                emoticonToolBar.switchSelectButton(indexPath!.section)
                
                // 设置pageControl的内容
                setupPageControl(indexPath!)
//                pageControl.numberOfPages = HMEmoticonManager.sharedManager.packageModels[indexPath!.section].pageEmoticons.count
//                pageControl.currentPage = indexPath!.item
                break
            }
        }
    }
    
    // 设置pageControl的内容
    private func setupPageControl(indexPath: NSIndexPath) {
        // 设置pageControl的内容
        pageControl.numberOfPages = HMEmoticonManager.sharedManager.packageModels[indexPath.section].pageEmoticons.count
        pageControl.currentPage = indexPath.item
        
        // 第0组不需要显示pageControl
        pageControl.hidden = indexPath.section == 0
    }
}

extension HMEmoticonKeyboard: HMEmoticonKeyboardPageCellDelegate {
    // 删除按钮被点击了
    func emoticonKeyboardPageCellDidClickDeleteButton(cell: HMEmoticonKeyboardPageCell) {
        // 删除textView的内容
        textView?.deleteBackward()
    }
    
    // 一个表情被点击了
    func emoticonKeyboardPageCell(cell: HMEmoticonKeyboardPageCell, didSelectedEmoticon: HMEmoticonModel) {
//        print("我在HMEmoticonKeyboard知道表情被点击了: \(didSelectedEmoticon)")
        // 往textView上面添加内容
        textView?.insertEmoticon(didSelectedEmoticon)
        
        // 添加到最近表情
        HMEmoticonManager.sharedManager.addRecentEmoticon(didSelectedEmoticon)
    }
    
//    /// 将模型的内容添加到textView上面
//    private func insertEmoticon(emoticon: HMEmoticonModel) {
//        // 1.emoji表情
//        if let emoji = emoticon.emoji {
//            textView?.insertText(emoji)
//            return
//        }
//        
//        // 2.图片表情
//        if let png = emoticon.fullPngPath {
//            // 将图片添加textView, textView可以显示属性文本
//            // 1.将图片添加到附件
//            let attachment = HMTextAttachment()
//            attachment.image = UIImage(named: png)
//            
//            // 把模型对应的名称发到附件中
//            attachment.chs = emoticon.chs
//            
//            // 1.1设置附件的bounds
//            let wh = textView?.font?.lineHeight ?? 15
//            // bounds.y 和 frame.y: frame往下走y是正数, bounds往下走y是负数
//            attachment.bounds = CGRect(x: 0, y: -5, width: wh, height: wh)
//            
//            // 2.将附件转成属性文本
//            let attrM = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
//            // 2.1 附件没有font属性跟在他后面的图片就会变的很小
//            attrM.addAttribute(NSFontAttributeName, value: textView!.font!, range: NSRange(location: 0, length: 1))
//            
//            // 2.2将带 图片的属性文本 ,替换现有文本光标位置
//            let currentText = NSMutableAttributedString(attributedString: textView!.attributedText)
//            
//            // 当前光标的位置
//            let currentSelectedRange = textView!.selectedRange
//            
//            currentText.replaceCharactersInRange(currentSelectedRange, withAttributedString: attrM)
//            
//            // 3.textView设置属性文本
//            textView?.attributedText = currentText
//            
//            // 设置光标的位置
//            textView?.selectedRange = NSRange(location: currentSelectedRange.location + 1, length: 0)
//        }
//    }
}